#include <stdlib.h>
#include <GL/glut.h>
#include <GL/glu.h>
#include <GL/gl.h>

#include "tgaimage.h"

char texFile[] = "head.tga";
GLuint maTexture;


void myinit(void)
{
	TGAImage *image  = new TGAImage();
	image->read_tga_file(texFile);

	glGenTextures(1, &maTexture);

	glBindTexture(GL_TEXTURE_2D,maTexture);
	
	glPixelStorei (GL_UNPACK_ALIGNMENT, 1);

    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->get_width(), image->get_height(),
		0, GL_RGB, GL_UNSIGNED_BYTE, image->get_data());

	delete image ;

	glEnable(GL_TEXTURE_2D);

}

void display(void)
{
	//Initialisation des pixels
	glClear (GL_COLOR_BUFFER_BIT);

	//Dessin du rectangle
	glBegin(GL_QUADS);
		glTexCoord2f(0.0,0.0) ; glVertex2f(-0.5,-0.5);
		glTexCoord2f(0.0,1.0) ; glVertex2f(-0.5,0.5);
		glTexCoord2f(1.0,1.0) ; glVertex2f(0.5,0.5);
		glTexCoord2f(1.0,0.0) ; glVertex2f(0.5,-0.5);
	glEnd();

	//Affichage forcé
	glFlush();
}


void clavier(unsigned char key,int x, int y)
{
	switch (key) {
		case(27) :
			glDeleteTextures(1,&maTexture);
			exit(0);
	}
}

int main(int argc, char** argv)
{

	//Démarrage de glut & création de la fenêtre 

	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_RGB);
	glutInitWindowPosition(100,100);
	glutInitWindowSize(800,800);
	glutCreateWindow("Test");
	

	myinit();


	//Création du fond noir
	glClearColor(0.0,0.0,0.0,0.0);

	//Utilisation de la fonction d'affichage
	glutDisplayFunc(display);
	glutKeyboardFunc(clavier);
	
	//Entrée dans la boucle d'attente
	glutMainLoop();

	return(0);

}
